﻿using ModernShopping.AppCode;
using ModernShopping.AppCode.WebUtil;
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using fhq.hcmute.core.qrcode;
using fhq.hcmute.core.qrcode.common;
using fhq.hcmute.desktop.image;
using System.IO;
namespace ModernShopping.User
{
    public partial class AddProducts : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            LoginInfo loginInfo = Session.GetLoginInfo();
            if (loginInfo == null)
            {
                Response.GoToAccessDeniedPage(Request);
            }
            if (!loginInfo.IsUser())
            {
                Response.GoToAccessDeniedPage(Request);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoginInfo loginInfo = Session.GetLoginInfo();
                DbStore.InitDropdownList(cboListStore, loginInfo.UserID);
                try
                {
                    int code = int.Parse(cboListStore.SelectedValue);
                    lblAddress.Text = DbStore.GetByID(code).Address;
                }
                catch
                {
                }
            }
        }

        private EntitySet<ProductStore> getProductStores()
        {
            EntitySet<ProductStore> productStores = new EntitySet<ProductStore>();
            List<Store> listStore = Session.GetListStore();
            foreach (Store st in listStore)
            {
                ProductStore ps = new ProductStore();
                ps.CodeStore = st.Code;
                productStores.Add(ps);
            }
            return productStores;
        }

        private string CreateQRCode(ProductMapping pm)
        {
            QRCodeWriter qrWriter = new QRCodeWriter(pm.ToString(), ErrorCorrectionLevel.H);
            QRCode qrcode = qrWriter.getQrCode(); ;
            BufferImageUtil.Builder builder = new BufferImageUtil.Builder(qrcode);
            builder.setDotSize(5);
            string ImageURL = string.Format("~/images/QrCode/{0}.png", pm.ProductCode);
            if (!File.Exists(Server.MapPath("~/images/QrCode")))
            {
                Directory.CreateDirectory(Server.MapPath("~/images/QrCode"));
            }
            builder.saveToFile(Server.MapPath(ImageURL));
            return ImageURL;
        }

        private void refreshDropdownList()
        {
            DbStore.RefreshDropdownList(cboListStore, Session.GetLoginInfo().UserID, Session.GetListStore());
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (edtDescription.Content.Length == 0)
            {
                MyPopup.InitPopup("Chưa nhập mô tả", "Vui lòng nhập chi tiết thông tin mô tả sản phẩm của bạn.", "red");
                MyPopup.Show();
                return;
            }

            if (FileUpload.HasFile == false)
            {
                MyPopup.InitPopup("Chưa có ảnh mô tả", "Vui lòng thêm ảnh mô tả cho sản phẩm", "red");
                MyPopup.Show();
                return;
            }

            string ImageUrl = "~/Images/Products/{0}{1}";
            Countdown.ShowPopup();
            Product product = new Product();
            product.Name = TxtProductName.Text;
            product.Price = double.Parse(TxtPrice.Text);
            product.Description = edtDescription.Content;
            product.MadeIn = TxtMadeIn.Text;
            product.CompanyCode = Session.GetLoginInfo().UserID;
            product.ProductStores = getProductStores();
            product.ImageUrl = "~/Images/Products/no-image.jpg";
            product.QrCode = "~/Images/Products/no-image.jpg";
            if (DbProduct.Add(product))
            {
                ImageUrl = String.Format(ImageUrl, product.Code, System.IO.Path.GetExtension(FileUpload.FileName));
                if (DbProduct.UpdateImage(product.Code, ImageUrl))
                {
                    FileUpload.SaveAs(Server.MapPath(ImageUrl));
                }
                ProductMapping productMapping = new ProductMapping();
                productMapping.ProductCode = product.Code;
                productMapping.ProductName = product.Name;
                productMapping.Price = double.Parse(TxtPrice.Text);
                productMapping.MadeIn = product.MadeIn;

                if (DbProduct.UpdateQRCode(product.Code, CreateQRCode(productMapping)))
                {
                    Countdown.InitCountdown(5, "Thêm thành công", "Hệ thống sẽ mở lại trang trong {0} giây nữa", WebUtil.Page.ADD_PRODUCT);
                    Countdown.Start();
                }
                else
                {
                    Countdown.HidePopup();
                    MyPopup.InitPopup("Thêm thất bại", "<Br/>Vui lòng kiểm tra lại thông tin sản phẩm", "red");
                    MyPopup.Show();
                }
            }
            else
            {
                Countdown.HidePopup();
                MyPopup.InitPopup("Thêm thất bại", "<Br/>Vui lòng kiểm tra lại thông tin sản phẩm", "red");
                MyPopup.Show();
            }
            Session.RemoveListStore();
        }

        protected void lbRemove_Click(object sender, EventArgs e)
        {
            LinkButton lb = (sender as LinkButton);
            int Code = int.Parse(lb.CommandArgument);
            if (Session.RemoveStore(Code))
            {
                RefreshGridview();
                refreshDropdownList();
            }
        }

        protected void cboListStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            int code = int.Parse(cboListStore.SelectedValue);
            lblAddress.Text = DbStore.GetByID(code).Address;
        }

        protected void btnInsertStore_Click(object sender, EventArgs e)
        {
            int code = int.Parse(cboListStore.SelectedValue);
            Session.AddStoreToList(DbStore.GetByID(code));
            RefreshGridview();
            cboListStore.Items.RemoveAt(cboListStore.SelectedIndex);
        }

        private void RefreshGridview()
        {
            List<Store> listStore = Session.GetListStore();
            gvMyStores.DataSource = listStore;
            gvMyStores.DataBind();
        }

        protected void gvMyStores_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvMyStores.PageIndex = e.NewPageIndex;
            RefreshGridview();
        }
    }
}